package com.zhangx.study.demo.mybatis.registrar;

import com.zhangx.study.demo.mybatis.bean.MyFactoryBean;
import com.zhangx.study.demo.mybatis.mapper.UserMapper;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @ClassName MyBeanDefinitionRegistrar
 * @Description bean注册
 * @Author zhangx
 * @Date 2021/5/18 10:12
 **/
public class MyBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
    @Override
    public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {
        Set<String> annoTypes = annotationMetadata.getAnnotationTypes();
        List<Class> classes = new ArrayList<>();
        classes.add(UserMapper.class);
        for (Class mapper:classes) {
//            创建一个个的bd
//            注意MyFactoryBean不能加component注解了，要通过这里创建bean
            BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition();
            AbstractBeanDefinition abstractBeanDefinition = beanDefinitionBuilder.getBeanDefinition();
            abstractBeanDefinition.setBeanClass(MyFactoryBean.class);
            abstractBeanDefinition.getConstructorArgumentValues().addGenericArgumentValue(mapper);
//            注册到factory
            beanDefinitionRegistry.registerBeanDefinition(mapper.getName(),abstractBeanDefinition);

        }
    }
}
